package com.example.unisys.controller;


import com.example.unisys.common.Response;
import com.example.unisys.common.STATUS;
import com.example.unisys.dao.ExamMapper;
import com.example.unisys.dao.HistStuCourseMapper;
import com.example.unisys.dao.StuExamMapper;
import com.example.unisys.entity.*;
import com.example.unisys.service.*;
import com.example.unisys.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.*;

@RestController
@RequestMapping(value = "/apis/v1/static", produces = "application/json; charset=utf-8")
public class FileController {

    @Autowired
    StudentService studentService;

    @Autowired
    TagService tagService;

    @Autowired
    StuCourseService stuCourseService;

    @Autowired
    SchoolNoService schoolNoService;

    @Autowired
    HistStuCourseMapper histStuCourseMapper;

    @Autowired
    StuExamMapper stuexamMapper;

    @Autowired
    CourseSaleService courseSaleService;

    @Autowired
    CourseService courseService;

    @Autowired
    ExamMapper examMapper;

    @Autowired
    SubCourseService subCourseService;


    //单独上传文件的接口，测试用，实际系统中并没有用到
    @RequestMapping(value = "/file", method = {RequestMethod.POST})
    public HashMap<String, Object> upload(@RequestParam("File") MultipartFile imgFile, HttpServletRequest request, HttpSession session) {

        HashMap<String, Object> res = new HashMap<>();
        String filename = imgFile.getOriginalFilename();
        File fileDir = UploadUtil.getImgDirFile();
        System.out.println(fileDir.getAbsolutePath());
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");

        try {

            String suffix = filename.substring(filename.indexOf("."), filename.length()).trim();
            File newFile = new File(fileDir.getAbsolutePath() + File.separator + uuid + suffix);
            System.out.println(newFile.getAbsolutePath());

            // 上传图片到 -》 “绝对路径”
            imgFile.transferTo(newFile);
            res.put("code", 20000);
            res.put("data", uuid + suffix);
            return res;

            //msg.setMsg("上传成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }

        res.put("code", 400);
        return res;

    }


    //上传学生表格，
    /*
     * 增加容错处理和失败信息返回
     * */
    @RequestMapping(value = "/upstu", method = {RequestMethod.POST})
    public Response upload(@RequestParam("File") MultipartFile excelFile, HttpServletRequest request) {
        HashMap<String, Object> res = new HashMap<>();

        List<Student> excel = new ArrayList<>();
        List<Student> fails = new ArrayList<>();

        try {
            //HashMap<String, String> hs = schoolNoService.getAll();
            //解析学生excel获取结果
            excel = ConfigExcelUtil.readExcel2(excelFile);
        } catch (Exception e) {
            e.printStackTrace();
            return Response.builder().status(STATUS.BAD_REQUEST).message(e.getMessage()).data(e.getMessage()).build();
        }
        for (Student a : excel) {
            /*
             * 操作记录日志，这里后面会写到mongoDb中
             * */
            System.out.println(a.toString());
        }
        Tag active_tag = tagService.getActiveTag();
        String tag = active_tag.getTag_name();
        for (Student stu : excel) {
            //将机构代码换成机构名字
            // String main_school = hs.get(stu.getMain_school());
            //String sub_school = hs.get(stu.getSub_school());
            //stu.setMain_school(main_school);
            //stu.setSub_school(sub_school);
                /*
                if (studentService.getById(stu.getExam_id()) != null) {
                    studentService.update(stu);
                } else {
                    stu.setTag(tag);
                    Date date = new Date(System.currentTimeMillis());
                    java.sql.Date sqlDate = new java.sql.Date(date.getTime());
                    stu.setRegister_date(sqlDate);
                    studentService.insertSelective(stu);
                }
                 */
            boolean ret_status;
            ret_status = insertStu(stu, tag);
            if (ret_status == false) fails.add(stu);
        }
        return Response.builder().status(STATUS.SUCCESS).data("插入成功").message("插入成功").build();

    }

    //@Transactional
    /*
     * 批量选课
     * */
    @RequestMapping(value = "/upstucourse", method = {RequestMethod.POST})
    public Response upStuCourse(@RequestParam("File") MultipartFile imgFile, HttpServletRequest request) {

        List<StuCourse> ls = ConfigExcelUtil.readCourseExcel(imgFile);
        ArrayList<String> failListInfo = new ArrayList<>();
        for (StuCourse sc : ls) {
            boolean ret_status = false;
            String exam_id = sc.getExam_id();
            String course_id = sc.getCourse_id();

            //System.out.println(exam_id +" "+course_id );
            if (course_id != null || exam_id != "")
                ret_status = addCourse(exam_id, course_id);
            if (ret_status == false)
                failListInfo.add("条目：考号:" + sc.getExam_id() + " 课程号：" + sc.getCourse_id());
        }
        System.out.println("fail num is" + BaseUtils.getFailListMessage(failListInfo));
        return Response.builder().status(STATUS.SUCCESS).total(failListInfo.size()).message(BaseUtils.getFailListMessage(failListInfo)).build();

    }

    /*
     *上传照片zip
     * */
    @RequestMapping(value = "/uploadzip", method = {RequestMethod.POST})
    public Response upload(@RequestParam("File") MultipartFile imgFile) {
        File tmpfile;
        try {
            tmpfile = FileUtil.multipartFileToFile(imgFile);
            File fileDir = UploadUtil.getPhotoPath();
            String filepath = fileDir.getAbsolutePath();
            System.out.println("photo path is " + filepath);
            ZipUtil.unZipFiles(tmpfile, filepath);

        } catch (Exception e) {
            e.printStackTrace();
            return Response.builder().status(STATUS.BAD_REQUEST).data("照片上传失败").build();

        }
        if (tmpfile != null)
            tmpfile.delete();
        return Response.builder().status(STATUS.SUCCESS).data("上传成功").build();
    }

 /*   @RequestMapping(value = "down_current", method = {RequestMethod.GET})
    public void downExcel(HttpServletResponse res, @RequestParam("main_school") String main_school, @RequestParam("sub_school") String sub_school) {
        Map<String, Object> map = new HashMap<>();
        if (main_school.equals(sub_school)) {
            //主校管理员
            map.put("main_school", main_school);
        } else if (main_school.equals("") && sub_school.equals("")) {
            //系统管理员
        } else {
            //分校管理员
            map.put("main_school", main_school);
            map.put("sub_school", sub_school);
        }

        List<Map<String, Object>> ls = stuCourseService.GetExcel(map);
        String filepath = ConfigExcelUtil.getStuCourseExcel(ls);


        if (filepath == null) {
            try {
                res.sendError(400, "生成文件失败");
            }catch (Exception e)
            {
                e.printStackTrace();
            }
            return;
        }
        BufferedInputStream bis = null;
        OutputStream os = null;
        File excelFile=null;
        try {
            excelFile = new File(filepath);
            String filename = excelFile.getName();
            res.setCharacterEncoding("UTF-8");
            res.setHeader("content-type", "application/octet-stream;charset=UTF-8");
            res.setContentType("application/octet-stream;charset=UTF-8");
            res.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(filename.trim(), "UTF-8"));
            byte[] buff = new byte[1024];
            os = res.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(new File(filepath)));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (Exception e) {
            e.printStackTrace();
            res.sendError(400, "生成文件失败");
            return;
        } finally {
            //删除临时生成的excel文件
            excelFile.delete();
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return;
        }
    }
*/

    /*
     * 下载当前学生成绩表
     * 根据不同管理员权限进行下载
     * old version
     * */
/*
    @RequestMapping(value = "down_current", method = {RequestMethod.GET})
    public void downExcel(HttpServletResponse res, @RequestParam("main_school") String main_school, @RequestParam("sub_school") String sub_school) {
        Map<String, Object> map = new HashMap<>();
        if (main_school.equals(sub_school)) {
            //主校管理员
            map.put("main_school", main_school);
        } else if (main_school.equals("") && sub_school.equals("")) {
            //系统管理员
        } else {
            //分校管理员
            map.put("main_school", main_school);
            map.put("sub_school", sub_school);
        }

        List<Map<String, Object>> ls = stuCourseService.GetExcel(map);
        String filepath = ConfigExcelUtil.getStuCourseExcel(ls);


        if (filepath == null) {
            try {
                res.sendError(400, "生成文件失败");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return;
        }
        BufferedInputStream bis = null;
        OutputStream os = null;
        File excelFile = null;
        try {
            excelFile = new File(filepath);
            String filename = excelFile.getName();
            res.setCharacterEncoding("UTF-8");
            res.setHeader("content-type", "application/octet-stream;charset=UTF-8");
            res.setContentType("application/octet-stream;charset=UTF-8");
            res.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(filename.trim(), "UTF-8"));
            byte[] buff = new byte[1024];
            os = res.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(new File(filepath)));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (Exception e) {
            e.printStackTrace();
            res.sendError(400, "生成文件失败");
            return;
        } finally {
            //删除临时生成的excel文件
            excelFile.delete();
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return;
        }
    }
*/

    /*
     * 下载当前学生成绩表
     * 根据不同管理员权限进行下载
     * new version
     * */
    @RequestMapping(value = "down_current", method = {RequestMethod.GET})
    public void downExcel_v1(HttpServletResponse res, @RequestParam("user_type") Integer user_type, @RequestParam("main_school") String main_school, @RequestParam("sub_school") String sub_school) {
        Map<String, Object> map = new HashMap<>();
        if (user_type == 2)
            //主校管理员
            map.put("main_school", main_school);
        else if (user_type == 3) {
            map.put("main_school", main_school);
            map.put("sub_school", sub_school);
        }

        List<Map<String, Object>> ls = stuCourseService.GetExcel(map);
        String filepath = ConfigExcelUtil.getStuCourseExcel(ls);


        if (filepath == null) {
            try {
                res.sendError(400, "生成文件失败");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return;
        }
        BufferedInputStream bis = null;
        OutputStream os = null;
        File excelFile = null;
        try {
            excelFile = new File(filepath);
            String filename = excelFile.getName();
            res.setCharacterEncoding("UTF-8");
            res.setHeader("content-type", "application/octet-stream;charset=UTF-8");
            res.setContentType("application/octet-stream;charset=UTF-8");
            res.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(filename.trim(), "UTF-8"));
            byte[] buff = new byte[1024];
            os = res.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(new File(filepath)));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (Exception e) {
            e.printStackTrace();
            res.sendError(400, "生成文件失败");
            return;
        } finally {
            //删除临时生成的excel文件
            excelFile.delete();
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return;
        }
    }


    /*
     * 下载历史学生成绩表
     * 根据不同管理员权限进行下载
     * old version
     * */
/*    @RequestMapping(value = "/down_history", method = {RequestMethod.GET})
    public void downloadStudentReport(HttpServletResponse res, @RequestParam("main_school") String main_school, @RequestParam("sub_school") String sub_school, @RequestParam("tag") String tag) {
        Map<String, Object> map = new HashMap<>();
        map.put("tag", tag);
        if (main_school.equals(sub_school)) {
            map.put("main_school", main_school);
            //主校管理员
        } else if (main_school.equals("") && sub_school.equals("")) {
            //系统管理员
        } else {
            //主校管理员
            map.put("main_school", main_school);
            map.put("sub_school", sub_school);
        }
        //List<Map<String, Object>> ls = stuCourseService.GetExcel(map);
        List<Map<String, Object>> ls = histStuCourseMapper.GetExcel(map);
        String filepath = ConfigExcelUtil.getStuCourseExcel(ls);
        if (filepath == null) {
            try {
                res.sendError(400, "生成文件失败");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return;
        }
        BufferedInputStream bis = null;
        OutputStream os = null;
        File excelFile = null;
        try {
            excelFile = new File(filepath);
            String filename = excelFile.getName();
            res.setCharacterEncoding("UTF-8");
            res.setHeader("content-type", "application/octet-stream;charset=UTF-8");
            res.setContentType("application/octet-stream;charset=UTF-8");
            res.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(filename.trim(), "UTF-8"));
            byte[] buff = new byte[1024];
            os = res.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(new File(filepath)));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (Exception e) {
            e.printStackTrace();
            res.sendError(400, "生成文件失败");
            return;
        } finally {
            //删除临时生成的excel文件
            excelFile.delete();
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return;
        }
    }*/

    /*
     * 下载历史学生成绩表
     * 根据不同管理员权限进行下载
     * new version
     * */
    @RequestMapping(value = "/down_history", method = {RequestMethod.GET})
    public void downloadStudentReport_v1(HttpServletResponse res, @RequestParam("user_type") Integer user_type, @RequestParam("main_school") String main_school, @RequestParam("sub_school") String sub_school, @RequestParam("tag") String tag) {
        Map<String, Object> map = new HashMap<>();
        map.put("tag", tag);
        if (user_type == 2)
            //主校管理员
            map.put("main_school", main_school);
        else if (user_type == 3) {
            map.put("main_school", main_school);
            map.put("sub_school", sub_school);
        }

        //List<Map<String, Object>> ls = stuCourseService.GetExcel(map);
        List<Map<String, Object>> ls = histStuCourseMapper.GetExcel(map);
        String filepath = ConfigExcelUtil.getStuCourseExcel(ls);
        if (filepath == null) {
            try {
                res.sendError(400, "生成文件失败");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return;
        }
        BufferedInputStream bis = null;
        OutputStream os = null;
        File excelFile = null;
        try {
            excelFile = new File(filepath);
            String filename = excelFile.getName();
            res.setCharacterEncoding("UTF-8");
            res.setHeader("content-type", "application/octet-stream;charset=UTF-8");
            res.setContentType("application/octet-stream;charset=UTF-8");
            res.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(filename.trim(), "UTF-8"));
            byte[] buff = new byte[1024];
            os = res.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(new File(filepath)));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (Exception e) {
            e.printStackTrace();
            res.sendError(400, "生成文件失败");
            return;
        } finally {
            //删除临时生成的excel文件
            excelFile.delete();
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return;
        }
    }


    /*
     * zerkvii
     * 下载督学
     * 根据权限
     * */
    @RequestMapping(value = "down_supervise", method = RequestMethod.GET)
    public void downloadSupervise(HttpServletResponse res,@RequestParam("user_type")Integer user_type, @RequestParam("main_school") String main_school, @RequestParam("sub_school") String sub_school) {
        HashMap<String, Object> hs = new HashMap<>();
        if (user_type == 2)
            //主校管理员
            hs.put("main_school", main_school);
        else if (user_type == 3) {
            hs.put("main_school", main_school);
            hs.put("sub_school", sub_school);
        }
        List<Map<String, Object>> students = studentService.getSuperviseFile(hs);
        String filepath = ConfigExcelUtil.getSuperviseExcel(students);
        if (filepath == null) {
            try {
                res.sendError(400, "生成文件失败");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return;
        }
        BufferedInputStream bis = null;
        OutputStream os = null;
        File excelFile = null;
        try {
            excelFile = new File(filepath);
            String filename = excelFile.getName();
            res.setCharacterEncoding("UTF-8");
            res.setHeader("content-type", "application/octet-stream;charset=UTF-8");
            res.setContentType("application/octet-stream;charset=UTF-8");
            res.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(filename.trim(), "UTF-8"));
            byte[] buff = new byte[1024];
            os = res.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(new File(filepath)));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (Exception e) {
            e.printStackTrace();
            res.sendError(400, "生成文件失败");
            return;
        } finally {
            //删除临时生成的excel文件
            excelFile.delete();
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return;
        }
    }

/*
    @RequestMapping(value = "down_current", method = {RequestMethod.GET})
    public HashMap<String,Object> downExcel(HttpServletResponse res, @RequestParam("main_school") String main_school, @RequestParam("sub_school") String sub_school) {
        HashMap<String,Object> res = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        if (main_school.equals(sub_school)) {
            //主校管理员
            map.put("main_school", main_school);
        } else if (main_school.equals("") && sub_school.equals("")) {
            //系统管理员
        } else {
            //分校管理员
            map.put("main_school", main_school);
            map.put("sub_school", sub_school);
        }

        List<Map<String, Object>> ls = stuCourseService.GetExcel(map);
        String filepath = ConfigExcelUtil.getStuCourseExcel(ls);
        if(filepath==null){
            res.put("code",400);
            res.put("data","生成失败");
        }


    }

 */


    //通过非url方式替学生选课，导入表格时要用


    //@Transactional(rollbackFor = Exception.class)
    /*
    * 选课函数*/
    public boolean addCourse(String exam_id, String course_id) {


        try {

            Student stu = studentService.getById(exam_id);

            //判断该学校是否已经选了这门课
            String main_school = stu.getMain_school();
            String sub_school = stu.getSub_school();
            SubCourse info = subCourseService.getById(main_school, sub_school, course_id);
            if (info == null) return false;

            courseSaleService.updateSale(course_id, stu.getMain_school(), stu.getSub_school());
            Course course = courseService.getById(course_id);
            StuCourse stuCourse = StuCourse.builder().build();
            stuCourse.setExam_id(exam_id);
            stuCourse.setCourse_id(course_id);
            stuCourse.setWatch_time(0);
            stuCourse.setReal_name(stu.getReal_name());
//            sc.setCourse_name(course.getCourse_name());
            stuCourse.setCatalogtree(course.getCatalogtree());
            stuCourse.setTotal_time(course.getNorm_duration());
            stuCourseService.insertSelective(stuCourse);
            List<Examination> exams = examMapper.selectByCourseid(course_id);
            exams.forEach(examination -> {
                StuExam stuExam = StuExam.builder().build();
                stuExam.setCourse_id(course_id);
                stuExam.setExam_content(examination.getExam_content());
                stuExam.setExam_id(exam_id);
                stuExam.setExam_title(examination.getExam_title());
                stuExam.setExam_type(examination.getExam_type());
                stuexamMapper.insertSelective(stuExam);
            });
//            for (int i = 0; i < exams.size(); i++) {
//                StuExam stuexam = StuExam.builder().build();
//                stuexam.setCourse_id(course_id);
//                stuexam.setExam_content(exams.get(i).getExam_content());
//                stuexam.setExam_id(exam_id);
//                stuexam.setExam_title(exams.get(i).getExam_title());
//                stuexam.setExam_type(exams.get(i).getExam_type());
//                stuexamMapper.insertSelective(stuexam);
//            }
        } catch (Exception e) {
            e.printStackTrace();
            // TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
        return true;
    }

    //@Transactional(rollbackFor = Exception.class)
    public boolean insertStu(Student stu, String tag) {
        try {
            if (studentService.getById(stu.getExam_id()) != null) {
                studentService.update(stu);
            } else {
                stu.setTag(tag);
                Date date = new Date(System.currentTimeMillis());
                java.sql.Date sqlDate = new java.sql.Date(date.getTime());
                stu.setRegister_date(sqlDate);
                studentService.insertSelective(stu);
            }
        } catch (Exception e) {
            e.printStackTrace();
            //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
        return true;
    }

}
